import { App } from 'whd-koa-base';
import * as Router from 'koa-router';
import * as bodyParserServ from 'koa-bodyparser';
import {
    jsonResponse, getLogger
} from 'whd-koa-util';
import * as path from 'path';
import * as fs from 'fs';
import { serverConfig } from './config';
import { SocketServer } from './socket/server';
import { RedisClient, createClient } from 'redis';
import { RedisHelper } from './redis/redis';
import { MyConnection } from './entity/connection';

SocketServer.getInstance((message: string) => { console.log(message); }, '8181').start();

RedisHelper.getInstance('121.43.186.164', 6379);

MyConnection.getInstance();

// 创建 app
const app = new App(serverConfig);
// 创建错误日志
const logPath = path.resolve(serverConfig.home, serverConfig.logPath);
const errorLogger = getLogger('error', logPath, 'error.log');
// 配置 JSON 中间件，并设置错误日志
app.use(jsonResponse(errorLogger));

// 设置请求解析中间件
app.use(bodyParserServ());

// 绑定处理路由
// map area routes in area direcroty
const routes = new Router();
const areaPath = fs.readdirSync(path.resolve(__dirname, 'area'));
areaPath.forEach((area: string) => {
    const define = () => import(`./area/${area}`);
    (async () => {
        const { default: router } = await define();
        routes.use(router.routes(), router.allowedMethods());
    })();
});
app.use(routes.routes()).use(routes.allowedMethods());

app.start();
